package com.woniuxy.project.campus.canteenOrder.controller;


import com.alipay.api.internal.util.AlipaySignature;
import com.woniuxy.project.campus.canteenModelform.SelectOrderByStateForm;
import com.woniuxy.project.campus.canteenOrder.config.AlipayConfiguration;
import com.woniuxy.project.campus.canteenOrder.dto.OrderInfoDto;
import com.woniuxy.project.campus.canteenOrder.dto.SelectOrderByStateDto;
import com.woniuxy.project.campus.canteenOrder.dto.Turnover;
import com.woniuxy.project.campus.canteenOrder.service.OrderInfoService;
import com.woniuxy.project.campus.canteenModelform.AddOrderForm;
import com.woniuxy.project.campus.canteenModelform.AlipayCallBackForm;
import com.woniuxy.project.campus.canteenModelform.OrderRequest;
import com.woniuxy.project.campus.util.Result;
import com.woniuxy.project.campus.util.TokenTool;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 猫将军
 * @since 2025年02月17日
 */
@RestController
@RequestMapping("/orderInfo")
public class OrderInfoController {


    @Resource
    private OrderInfoService orderInfoService;

    @Resource
    private AlipayConfiguration alipayConf;


    //下单

    @ApiOperation(value = "下单")
    @RequestMapping("/addOrder")
    public Result addOrder(@RequestHeader("token") String token,@RequestBody AddOrderForm form) throws Exception {
        System.out.println("form"+form.getProductIds());
        System.out.println("form"+form.getAccountName());
        System.out.println("form"+form.getPhone());
        System.out.println("form"+form.getAddress());
        System.out.println("form"+form.getRemark());
        Integer accountId = TokenTool.getUserIdByToken(token);
        OrderInfoDto orderInfoDto = orderInfoService.addOrder(accountId,form);
        return Result.success(orderInfoDto);
    }


    //支付订单
    @ApiOperation(value = "支付订单")
    @PostMapping("/payOrder")
    public Result payOrder(@RequestHeader("token") String token,@RequestBody OrderRequest orderRequest) throws Exception {
        Integer accountId = TokenTool.getUserIdByToken(token);
        String orderNum = orderRequest.getParams().getOrderNum();
        System.out.println("订单号******************"+orderNum);
        System.out.println("用户id1111111111111111111111111111111111111111111111111*"+accountId);
       String result = orderInfoService.payOrder(accountId,orderNum);



        return Result.success(result);
    }

    //支付回调
    @ApiOperation(value = "支付回调")
    @PostMapping("/payCallback")
    public String payCallback(AlipayCallBackForm payResult , HttpServletRequest request) throws Exception {
        System.out.println("payCallback+·++++++++++++++++++++++++++++++++++++++++++++++++=");
        System.out.println("sssssssssssss" + payResult);
        //判断是否支付成功
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        if (AlipaySignature.rsaCheckV1(params, alipayConf.getAlipayPublicKey(), "utf-8", "RSA2")) {
            //验签成功
            if ("TRADE_SUCCESS".equals(payResult.getTrade_status())) {
                String tradeNo = payResult.getOut_trade_no();
                System.out.println("支付成功，订单号：" + tradeNo);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date panyDate = sdf.parse(String.valueOf(payResult.getGmt_payment()));
                LocalDateTime localDateTime = LocalDateTime.ofInstant(panyDate.toInstant(), ZoneId.systemDefault());
                //执行业务逻辑
                orderInfoService.updateOrderState(payResult.getOut_trade_no(),localDateTime);
                return "success";
            }
        }
        throw new Exception("非法请求");
    }




    //查询待支付订单
    @ApiOperation(value = "查询:待支付订单")
    @GetMapping("/selectOrderByState")
    public Result selectOrderByState(@RequestHeader("token") String token) throws Exception {
        Integer accountId = TokenTool.getUserIdByToken(token);
       List<SelectOrderByStateDto> orderInfoDtos = orderInfoService.selectOrderByState(accountId);
        return Result.success(orderInfoDtos);
    }

//    获取今日总收入的接口


    @ApiOperation(value = "获取今日总收入")
    @GetMapping("/getTodayTotalIncome")
    public Result getTodayTotalIncome(@RequestHeader("token") String token) throws Exception {
        Integer accountId = TokenTool.getUserIdByToken(token);
        String totalIncome = orderInfoService.getTodayTotalIncome(accountId);
        return Result.success(totalIncome);
    }

    
    //查询待接单订单
    @ApiOperation(value = "查询:待接单订单")
    @GetMapping("/selectOrderByState1")
    public Result selectOrderByState1(@RequestHeader("token") String token) throws Exception {
        Integer accountId = TokenTool.getUserIdByToken(token);
        List<SelectOrderByStateForm> orderInfoDtos = orderInfoService.selectOrderByState1(accountId);
        return Result.success(orderInfoDtos);
    }
}

